package com.cqndt.disaster.device.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class FileUpload {

    private static Logger logger = LoggerFactory.getLogger(FileUpload.class);

    /**
     * @param file           上传文件
     * @param attachmentType 文件类型（1.图片 2.视频 3.文件）
     * @param modelName      模块名称
     * @return
     */
    public static Result fileUpload(MultipartFile file, String attachmentType, String modelName, String attachmentUrlSet,
                                    String openOfficePath, String openOfficeHost, String fileIp, String newName) {
        if (null == attachmentType) {
            return new Result().failure(-1, "请选择文件类型");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        Boolean flag = isEquals(attachmentType, suffixName);
        if (!flag) {
            return new Result().failure(-1, "请上传正确的类型");
        }
        //保存路径
        String filePath = null;
        if ("2".equals(attachmentType)) {
            filePath = "video";
        } else if ("3".equals(attachmentType)) {
            filePath = "file";
        } else {
            filePath = "img";
        }
        //数据库存放路径
        String attachmentUrl = null;
        if (null != modelName && !("").equals(modelName)) {
            filePath = filePath + File.separator + modelName;
            attachmentUrl = modelName;
        }
        // 解决文件名重复问题 -- 解决中文问题，liunx下中文路径，图片显示问题
        String attachmentId = UUID.randomUUID().toString();
        attachmentUrl = attachmentUrl + File.separator + attachmentId + suffixName;
        filePath = filePath + File.separator + attachmentId;
        File dest = new File(attachmentUrlSet + File.separator + filePath + suffixName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        // 存储文件
        try {
            file.transferTo(dest);
            //如果为word文件则转换为pdf
            if (suffixName.equalsIgnoreCase(".doc") || suffixName.equalsIgnoreCase(".docx")
                    || suffixName.equalsIgnoreCase(".xls") || suffixName.equalsIgnoreCase(".xlsx")
                    || suffixName.equalsIgnoreCase(".ppt") || suffixName.equalsIgnoreCase(".pptx")) {
                String sourceFile = attachmentUrlSet + File.separator + filePath + suffixName;
                String destFile = attachmentUrlSet + File.separator + filePath + ".pdf";
                suffixName = ".pdf";
                int i = FileConverter.office2PDF(sourceFile, destFile, openOfficePath, openOfficeHost);
                if (i != 0) {
                    logger.error("转换异常");
                }
            }
        } catch (Exception e) {
            return new Result().failure(-1, "上传失败,请重新上传");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("attachmentType", attachmentType);
        map.put("id", attachmentId);
        map.put("attachmentName", null != newName ? newName : fileName);
        map.put("attachmentUrl", attachmentUrl);
        map.put("viewUrl", fileIp + File.separator + filePath + suffixName);
        return new Result().success(map);
    }

    /**
     * 上传类型控制
     *
     * @param attachmentType 附件类型
     * @param suffixName     附件后缀名
     * @return
     */
    private static Boolean isEquals(String attachmentType, String suffixName) {
        Boolean flag = true;
        if ("1".equals(attachmentType)) {
            flag = suffixName.equalsIgnoreCase(".jpg") || suffixName.equalsIgnoreCase(".png")
                    || suffixName.equalsIgnoreCase(".gif") || suffixName.equalsIgnoreCase(".tif")
                    || suffixName.equalsIgnoreCase(".jpeg") || suffixName.equalsIgnoreCase(".svg")
                    || suffixName.equalsIgnoreCase(".bmp") || suffixName.equalsIgnoreCase(".webp");
        } else if ("3".equals(attachmentType)) {
            flag = suffixName.equalsIgnoreCase(".doc") || suffixName.equalsIgnoreCase(".docx")
                    || suffixName.equalsIgnoreCase(".xls") || suffixName.equalsIgnoreCase(".xlsx")
                    || suffixName.equalsIgnoreCase(".ppt") || suffixName.equalsIgnoreCase(".pptx")
                    || suffixName.equalsIgnoreCase(".pdf") || suffixName.equalsIgnoreCase(".zip")
                    || suffixName.equalsIgnoreCase(".rar") || suffixName.equalsIgnoreCase(".7z")
                    || suffixName.equalsIgnoreCase(".ace") || suffixName.equalsIgnoreCase(".arj")
                    || suffixName.equalsIgnoreCase(".bz2") || suffixName.equalsIgnoreCase(".cab")
                    || suffixName.equalsIgnoreCase(".gz") || suffixName.equalsIgnoreCase(".iso")
                    || suffixName.equalsIgnoreCase(".tar") || suffixName.equalsIgnoreCase(".uue")
                    || suffixName.equalsIgnoreCase(".z") || suffixName.equalsIgnoreCase(".txt");
        } else {
            flag = suffixName.equalsIgnoreCase(".mp4") || suffixName.equalsIgnoreCase(".avi")
                    || suffixName.equalsIgnoreCase(".rmvb") || suffixName.equalsIgnoreCase(".mkv")
                    || suffixName.equalsIgnoreCase(".ogg")
                    || suffixName.equalsIgnoreCase(".flv")
                    || suffixName.equalsIgnoreCase(".wmv");
        }
        return flag;
    }

    /**
     * @param file 全景图上传
     * @return
     */
    public static Result fileUploadTwoRound(MultipartFile file, String attachmentUrlSet, String fileIp, String newName) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        // 解决文件名重复问题 -- 解决中文问题，liunx下中文路径，图片显示问题
        String attachmentId = UUID.randomUUID().toString();
        File dest = new File(attachmentUrlSet + File.separator + "twoRound" + File.separator + attachmentId + suffixName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        // 存储文件
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            return new Result().failure(-1, "上传失败,请重新上传");
        }
        //解压路径
        String unZipPath = attachmentUrlSet + File.separator + "twoRound" + File.separator + attachmentId + File.separator;
        String url = null;
        int type;
        try {
            url = UZipFileUtil.unZipFiles(dest, unZipPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (url.endsWith("html")) {
            type = 1;
        } else {
            type = 0;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("twoRoundUrl", "twoRound" + File.separator + attachmentId + File.separator + url);
        map.put("twoRoundName", null != newName ? newName : fileName);
        map.put("fileFullPath", fileIp + File.separator + "twoRound" + File.separator + attachmentId + File.separator + url);
        map.put("type", type);
        return new Result().success(map);
    }


    /**
     *
     * @param file 上传文件
     * @param attachmentType 文件类型（1.图片 2.视频 3.文件）
     * @param tempAttachmentUrl 上传文件临时路径
     * @return
     *//*
    public static Result fileUpload(MultipartFile file,String attachmentType,String tempAttachmentUrl) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        Boolean flag = isEquals(attachmentType,suffixName);
        if(!flag){
            return new Result().failure(-1,"请上传正确的类型");
        }
        // 解决文件名重复问题 -- 解决中文问题，liunx下中文路径，图片显示问题
        String attachmentId = UUID.randomUUID().toString();
        String filePath = attachmentId + suffixName;
        File dest = new File(tempAttachmentUrl + File.separator + filePath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        // 存储文件
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            return new Result().failure(-1,"上传失败,请重新上传");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("attachmentType", attachmentType);
        map.put("attachmentId", attachmentId);
        map.put("name", fileName);
        map.put("url", filePath);
        return new Result().success(map);
    }
*/
}
